import 'dart:io';

import 'package:applovin_max/applovin_max.dart';
import 'package:bitcoin_mine/common/global.dart';
import 'package:bitcoin_mine/controllers/contract_service_controller.dart';
import 'package:bitcoin_mine/services/in_app_purchase_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../widgets/bottom_navigation.dart';
import '../controllers/main_controller.dart';
import 'home_page.dart';
import 'contract_page.dart';
import 'fission_page.dart';
import 'wallet_page.dart';
import 'settings_page.dart';

class MainPage extends GetView<MainController> {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(ContractServiceController());
    Get.put(InAppPurchaseService());
    final MainController mainController = Get.put(MainController());
    final InAppPurchaseService inAppPurchaseService =
        Get.find<InAppPurchaseService>();
    mainController.active();
    Global.updateMineInfo().then((_) {
      inAppPurchaseService.loadProducts();
    });
    // 页面列表
    final List<Widget> pages = [
      const HomePage(),
      const ContractPage(),
      const FissionPage(),
      const WalletPage(),
      const SettingsPage(),
    ];

    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              const Color(0xFF0A0E27),
              const Color(0xFF1A1F3A),
              const Color(0xFF0A0E27),
            ],
          ),
        ),
        child: Column(
          children: [
            // 页面内容区域
            Expanded(
              child: Obx(
                () => IndexedStack(
                  index: mainController.currentIndex.value,
                  children: pages,
                ),
              ),
            ),
            buildAdView(),
            // 底部导航栏
            const BottomNavigation(),
          ],
        ),
      ),
    );
  }
}

final String ad_unit_ID =
    Platform.isAndroid ? "«Android-ad-unit-ID»" : "7bc310663a911c0d";
Widget buildAdView() {
  return MaxAdView(
    adUnitId: ad_unit_ID,
    adFormat: AdFormat.banner,
    listener: AdViewAdListener(
      onAdLoadedCallback: (ad) {
        print('Ad loaded');
      },
      onAdLoadFailedCallback: (adUnitId, error) {
        print('Ad load failed-${error.code}-${error.message}');
      },
      onAdClickedCallback: (ad) {
        print('Ad clicked');
      },
      onAdExpandedCallback: (ad) {
        print('Ad expanded');
      },
      onAdCollapsedCallback: (ad) {
        print('Ad collapsed');
      },
    ),
  );
}
